using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Data;
using System.Diagnostics;
using System.IO;


namespace QuanLyTruongHoc_App
{
    public partial class LuuTruCSDL : Form
    {
        //private databaseManagement db;
        private const String MSG_CONFIRM = "Để thực hiện thao tác này cần khởi động lại chương trình!\n" + 
                                           "Bạn có muốn khởi động lại ngay không?";
        private const String MSG_CONFIRM_RESTORE = "Tất cả dữ liệu hiện tại sẽ bị xóa.\nBạn có chắc muốn thực hiện thao tác này không?";
        //private const String MSG_CONFIRM_KET_SO = "Thao tác này sẽ thực hiện xóa các hóa đơn, tổng hợp nợ cho đầu kỳ tới ..." + 
        //                                          "\nBạn có chắc muốn thực hiện thao tác này hay không?";

        private const String BACKUP_OK = "Đã lưu trữ dữ liệu!";
        private const String RESTORE_OK = "Đã khôi phục dữ liệu!";
        private const String MSG_KHONG_TON_TAI = " Không tồn tại!";
        public const String RESTORE_FILE = "aijkij.sys";

        private String DB_SERVER, DB_NAME, DB_USER, DB_PASS;
        //public delegate void Evt_KetSo(object sender);
        //public event Evt_KetSo evt_KetSo;

        public static String getRestoreFilePath()
        {
            return Application.StartupPath + "\\" + RESTORE_FILE;
        }

        public LuuTruCSDL()
        {
            InitializeComponent();
            readConnectInfo();
            tb_dbName.Text = DB_NAME;
        }

        private void checkUserPower()
        {
            int pow = PublicLib.getUserPower(PConst.QUYEN_BACK_UP_DB);
            // user co quyen view
            //tscb_User.Enabled = ((pow & PConst.POW_VIEW) > 0);
            // user co quyen them
            //tsb_TaoMoi.Enabled = ((pow & PConst.POW_ADD) > 0);
            // user co quyen edit
            grb_BackUp.Enabled = ((pow & PConst.POW_EDIT) > 0);
            // user co delete
            grc_CleanUp.Enabled = ((pow & PConst.POW_DEL) > 0);
        }

        private void readConnectInfo()
        {
            if (!System.IO.File.Exists(SysConfig.getConfigFilePath())) return;

            StreamReader r = File.OpenText(SysConfig.getConfigFilePath());
            r.ReadLine(); // provider
            DB_SERVER = CryptorEngine.Decrypt(r.ReadLine(), true);
            DB_NAME = CryptorEngine.Decrypt(r.ReadLine(), true);
            DB_USER = CryptorEngine.Decrypt(r.ReadLine(), true);
            DB_PASS = CryptorEngine.Decrypt(r.ReadLine(), true);
            r.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            this.Visible = false;
            e.Cancel = true;
            //base.OnClosing(e);
        }
        // radio button
        private void rbt_Restore_CheckedChanged(object sender, System.EventArgs e)
        {
            this.btnSubmit.Text = "Khôi phục";

        }

        //Back-Up Selected
        private void rbt_backup_CheckedChanged(object sender, System.EventArgs e)
        {
            this.btnSubmit.Text = "Lưu trữ";
        }
        // Browse for file
        private void btnFile_Click(object sender, System.EventArgs e)
        {
            if (this.rbt_BackUp.Checked)
            {
                //backup
                this.saveFileDialog1.FileName = "QLTH" + DateTime.Now.ToString("-yyyy-MM-dd") + ".bak";
                saveFileDialog1.Filter = "BAK FILE (*.bak)|*.bak";
                if (this.saveFileDialog1.ShowDialog() != DialogResult.Cancel)
                {
                    if (this.saveFileDialog1.FileName != "")
                        this.txtFile.Text = this.saveFileDialog1.FileName;
                }
            }
            else
            {
                //restore
                //this.openFileDialog1.FileName = "hanet_rem.bak";
                openFileDialog1.Filter = "BAK FILE (*.bak)|*.bak";
                openFileDialog1.Multiselect = false;
                if (this.openFileDialog1.ShowDialog() != DialogResult.Cancel)
                {
                    if (this.openFileDialog1.FileName != "")
                        this.txtFile.Text = this.openFileDialog1.FileName;
                }
            }
        }
        // Connect
        //Get the databases and put into a combobox
        private void connectDB()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
                srv.Connect(DB_SERVER, DB_USER, DB_PASS);
                this.Cursor = Cursors.Default;
            }
            catch (Exception err)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(MSG.LOI_KET_NOI_BACK_UP + "\n" + err.Message, "Loi");
            }
        }
        // ------------------------------------
        //perform the backup/restore
        private void btnSubmit_Click(object sender, System.EventArgs e)
        {
            if (this.rbt_BackUp.Checked)
                BackUp();
            else
                Restore();
        }

        private void BackUp()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                //create an instance of a server class
                SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
                //connect to the server
                srv.Connect(DB_SERVER, DB_USER, DB_PASS);
                //create a backup class instance
                SQLDMO.Backup bak = new SQLDMO.BackupClass();
                //set the backup device = files property ( easy way )
                bak.Devices = bak.Files;
                //set the files property to the File Name text box
                bak.Files = this.txtFile.Text;
                //set the database to the chosen database
                bak.Database = DB_NAME;
                //perform the backup
                bak.SQLBackup(srv);
                MessageBox.Show(BACKUP_OK, "Thong Bao");
                this.Cursor = Cursors.Default;
            }
            catch (Exception err)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(err.Message, "Error");
                return;
            }

            //if (MessageBox.Show(MSG_CONFIRM_KET_SO, "Thong Bao", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //    evt_KetSo(this);

        }

        private void Restore()
        {
            if (!System.IO.File.Exists(txtFile.Text))
            {
                MessageBox.Show("File: '" + txtFile.Text + "'" + MSG_KHONG_TON_TAI);
                return;
            }

            if (MessageBox.Show(MSG_CONFIRM_RESTORE, "Thong Bao", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            System.IO.StreamWriter w = new StreamWriter(getRestoreFilePath());
            w.WriteLine(CryptorEngine.Encrypt(txtFile.Text, true));
            w.Close();
            if (MessageBox.Show(MSG_CONFIRM, "Thong Bao", MessageBoxButtons.YesNo) == DialogResult.Yes)
                Application.Restart();
        }

        public void DoRestore()
        {
            try
            {
                if (!System.IO.File.Exists(getRestoreFilePath())) return;

                StreamReader r = File.OpenText(getRestoreFilePath());

                this.Cursor = Cursors.WaitCursor;
                //create an instance of a server class
                SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
                //connect to the server
                srv.Connect(DB_SERVER, DB_USER, DB_PASS);
                //create a restore class instance
                SQLDMO.Restore res = new SQLDMO.RestoreClass();
                //set the backup device = files property ( easy way )
                res.Devices = res.Files;
                //set the files property to the File Name text box
                //res.Files = this.txtFile.Text;
                res.Files = CryptorEngine.Decrypt(r.ReadLine(), true);
                r.Close();
                
                if (!System.IO.File.Exists(res.Files))
                {
                    this.Cursor = Cursors.Default;
                    return;
                }
                //set the database to the chosen database
                res.Database = DB_NAME;
                // Restore the database
                res.ReplaceDatabase = true;
                //res.
                res.SQLRestore(srv);
                MessageBox.Show(RESTORE_OK, "Thong Bao");
                this.Cursor = Cursors.Default;
                //db.connectDatabase();
                System.IO.File.Delete(getRestoreFilePath());
            }
            catch (Exception err)
            {
                
                MessageBox.Show(err.Message, "Error");
                //db.connectDatabase();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //if (MessageBox.Show(MSG_CONFIRM_KET_SO, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //{
                BackUp();
            //}
            /*
            if (MessageBox.Show(MSG_CONFIRM_KET_SO, "Thong Bao", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                evt_KetSo(this);
            }*/
        }

        private void KetSo_Shown(object sender, EventArgs e)
        {
            txtFile.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "qlth.bak";
            //Application.ExecutablePath + "\\hanet_rem.bak";
        }

        private void LuuTruCSDL_Activated(object sender, EventArgs e)
        {
            checkUserPower();
        }
    }
}